﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using MvcEngine.Core;

using MvcEngine.Core.Repositories;
using MvcEngine.Mvc.Models.ViewModels;
using MvcEngine.Mvc.Filters;
using MvcEngine.Mvc.Extensions;
using MvcEngine.Core.Services;
using MvcEngine.Core.Content;
using MvcEngine.Mvc.Controllers;
using MvcEngine.Mvc.Models;
using MvcEngine.Core.Account;

namespace MvcEngine.Mvc.BackOffice.Controllers
{
    public class PageContentController : BaseController
    {
        [AcceptVerbs(HttpVerbs.Get)]
        public MvcEngineModel Design(Guid pageId, string mode)
        {
            PageContentViewModel model = new PageContentViewModel()
            {
                Mode = mode,
                Page = ContentManager.Current.GetPage(pageId),
                Modules = ContentManager.Current.GetModules(true),
                PageContents = ContentManager.Current.GetPageContents(pageId),
                Pages = ContentManager.Current.GetPages(false),
                Containers = ContentManager.Current.GetContainers(),
                Controls = ContentManager.Current.GetControls()
            };
            return new MvcEngineModelItem<PageContentViewModel>() { Item = model };
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public object InstallModule(Guid pageId, Guid moduleId, string commandName)
        {
            var module = ContentManager.Current.GetModule(moduleId);

            var defaultControl = ContentManager.Current.GetControls(moduleId).SingleOrDefault(c => !c.Visible);
            if (defaultControl == null)
            {
                //throw new MvcEngineConfigurationException();
            }

            var command = CommandRegistrator.Current.GetCommand(defaultControl.Id, commandName);
            if (command == null)
            {
#warning throw exception;
            }

            return Text(command.GetUrl(this.ControllerContext.RequestContext));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [JsonActionFilter(typeof(List<PageContentSaveViewModel>), "contents")]
        public object Save(Guid pageId, List<PageContentSaveViewModel> contents)
        {
            var pageContents = ContentManager.Current.GetPageContents(pageId);
            if (pageContents.Count > 0)
            {
                foreach (var item in pageContents)
                {
                    var content = contents.FirstOrDefault(c => c.CtrId == item.Id);
                    if (content != null)
                    {
                        var container = ContentManager.Current.GetContainer(content.MarkupId);
                        if (container != null)
                        {
                            item.Position = content.OrderNumber;
                            item.ContainerId = container.Id;
                        }
                    }
                }

                using (IUnitOfWork unitOfwork = UnitOfWorkHelper.Get())
                {
                    foreach (var item in pageContents)
                    {
                        ContentManager.Current.SavePageContent(item);
                    }
                    unitOfwork.Commit();
                }
            }
            return Json(new { result = "success" });
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete(int id)
        {

            PageContent content = ContentManager.Current.GetPageContent(id);
            Control control = ContentManager.Current.GetControl(content.ControlId);

            IControlService service = (IControlService)IoC.Resolve(Type.GetType(control.ControlServiceType));
            using (IUnitOfWork unitOfwork = UnitOfWorkHelper.Get())
            {
                var command = CommandRegistrator.Current.GetCommand(control.Id, "delete");
                if (command != null)
                {
                    //command.
                }
                unitOfwork.Commit();
            }

            return Redirect(Url.PageTemplate(content.PageId));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Rename(int ctrId, string name)
        {
            PageContent content = ContentManager.Current.GetPageContent(ctrId);
            content.ContentName = name;
            ContentManager.Current.SavePageContent(content);

            return Json(new { model = "valid" });
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public object Permissions(int id)
        {
            var controlPermissions = AccountManager.Current.GetControlPermissions(id);
            var permissions = AccountManager.Current.GetPermissions();
            var roles = AccountManager.Current.GetRoles();

            return new ModulePermissionViewModel()
            {
                ControlPermissions = controlPermissions,
                Permissions = permissions,
                Roles = roles,
                CtrId = id
            };
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ActionName("Permissions")]
        public object PermissionsSave(int id, PermissionViewModel[] permissions)
        {
            var controlPermissions = AccountManager.Current.GetControlPermissions(id);

            using (IUnitOfWork unitOfWork = UnitOfWorkHelper.Get())
            {
                foreach (var permission in permissions)
                {
                    var item = controlPermissions.SingleOrDefault(c => c.PermissionId == permission.Id && c.RoleId == permission.RoleId);
                    if (item != null)
                    {
                        if (!permission.Selected)
                        {
                            AccountManager.Current.DeleteControlPermission(id, permission.Id, permission.RoleId);
                        }
                    }
                    else
                    {
                        if (permission.Selected)
                        {
                            var newPermission = IoC.Resolve<ControlPermission>();
                            newPermission.Id = Guid.NewGuid();
                            newPermission.PageContentId = id;
                            newPermission.PermissionId = permission.Id;
                            newPermission.RoleId = permission.RoleId;
                            newPermission.CreatedBy = UserContext.Current.User.Id;
                            newPermission.CreatedDate = DateTime.Now;
                            newPermission.ModifiedBy = UserContext.Current.User.Id;
                            newPermission.ModifiedDate = DateTime.Now;
                            AccountManager.Current.AddControlPermission(newPermission);
                        }
                    }
                }
                unitOfWork.Commit();
            }

            return Json(new { model = "valid" });
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Add(Guid pageId, Guid controlId, Guid containerId)
        {
            var control = ContentManager.Current.GetControl(controlId);

            PageContent newPageContent = IoC.Resolve<PageContent>();
            newPageContent.PageId = pageId;
            newPageContent.ControlId = controlId;
            newPageContent.ContainerId = containerId;
            newPageContent.ContentName = control.Name;
            newPageContent.SiteId = SiteContext.Current.Site.Id;
            newPageContent.CreatedDate = DateTime.Now;
            newPageContent.ModifiedDate = DateTime.Now;
            newPageContent.CreatedBy = UserContext.Current.User.Id;
            newPageContent.ModifiedBy = UserContext.Current.User.Id;
            IoC.Resolve<IPageContentRepository>().Save(newPageContent);

            return Redirect(Url.PageTemplate(pageId));
        }


    }
}
